package com.wskeee.ec.components.tree
{
	import flash.utils.Dictionary;
	
	import com.wskeee.ec.interfaces.IList;

	public class TreeDataManager
	{
		private var dataToListData:Dictionary = new Dictionary(true);
		public var rootData:TreeListData;
		
		private var _data:Object;
		private var _list:IList;
		
		public function init(data:Object,list:IList):void
		{
			_data = data;
			_list = list;
			
			for(var i:Object in dataToListData)
				delete dataToListData[i];
			
			rootData = createData(data);
		}
		
		private function createData(data:Object,parent:TreeListData=null,depth:int=0):TreeListData
		{
			var isXML:Boolean = data is XML;
			if(!isXML)
			{
				if(typeof(data) == "string")
				{
					try
					{
						var tdata:XML = new XML(data);
					} 
					catch(err:Error) 
					{
						throw new Error("分析数据出错"+err.message);
						data = {label:" "};
					};
				}
				
				isXML = tdata!=null;
				if(isXML)
					data = tdata;
			}
			
			var label:String = isXML ? String(data.attribute(_list.labelField)) : data[_list.labelField];
			var treeData:TreeListData = new TreeListData(label,_list,parent,depth,data);
			if((isXML && data.hasComplexContent()) || (data.children && data.children.length!=0))
			{
				var len:int = isXML ? data.children().length() : data.children.length;
				var children:Vector.<TreeListData> = new Vector.<TreeListData>(len);
				var item:TreeListData;
				depth ++;
				for(var i:int=0;i<len;i++)
				{
					item = createData(isXML ? data.children()[i] : data.children[i],treeData,depth);
					children[i] = item;
				}
				treeData.children = children;
			}
			dataToListData[data] = treeData;
			return treeData;
		}
		
		/**
		 * 获取 tree data 转换成 list data 后的数据，转换后以Array返回 
		 * @return [object,object,,,]
		 * 
		 */
		public function getTreeDataToListData():Array
		{
			var arr:Array = [];
			getTreeDataForArray(arr,rootData);
			return arr;
		}
		
		private function getTreeDataForArray(arr:Array,treedata:TreeListData):void
		{
			arr.push(treedata.data);
			if((treedata.isOpen || (treedata == rootData && !Tree(_list).showRoot)) && treedata.hasChildren)
			{
				for(var i:int=0,len:int=treedata.children.length;i<len;i++)
					getTreeDataForArray(arr,treedata.children[i]);
			}
		}
		
		/**
		 * 获取 data 对应的 listData 
		 * @param data
		 * @return 
		 * 
		 */
		public function getListDataForData(data:Object):TreeListData
		{
			return dataToListData[data];
		}
	}
}